package com.yami.shop.otherservice;

import cn.hutool.core.bean.BeanUtil;
import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.dto.UserVipLevelDto;
import com.yami.shop.bean.enums.UserFundDetailEnum;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserFundDetail;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserFundDetailService;
import com.yami.shop.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 三级分销功能
 */
@Service
public class ThreeLevelDistributionService {
    @Autowired
    private OrderService orderService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserService userService;

    @Autowired
    private UserFundDetailService userFundDetailService;

    @Autowired
    private OrderItemService orderItemService;

    public void grantReward(String orderId) {
        com.yami.shop.bean.model.Order byId = orderService.getById(orderId);
        if(byId == null){
            throw new RuntimeException("订单收货成功 事件 查询订单为空");
        }

        System.out.println("收货成功");

        //下单用户
        User byId0 = userService.getById(byId.getUserId());

        if(byId0 == null){
            return;
        }

        String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
        List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));

        List<OrderItem> oi = orderItemService.lambdaQuery().eq(OrderItem::getOrderNumber, byId.getOrderNumber()).list();
        List<String> collect = oi.stream().map(o -> o.getProdId()).map(p -> String.valueOf(p)).collect(Collectors.toList());

        //在用户下单的订单中,找是否存在开启分销的商品
        List<String> collect1 = collect.stream().filter(op -> prodIds.contains(op)).collect(Collectors.toList());

        if(!collect1.isEmpty()){
            //购买了有分销奖励的商品
            String level1 = this.getValueByConfig("level1");
            String level2 = this.getValueByConfig("level2");
            String level3 = this.getValueByConfig("level3");

            List<UserVipLevelDto>  list1=userService.getHigherLevelVip(byId0.getUserId());
            if(byId0.getVipLevel() == null){
                //下单用户无vip等级
                //如果同一订单下单了多件参与三级分销的商品,则多次奖励
                for(String prodId : collect1){
                    UserVipLevelDto user0 = list1.stream().filter(d -> d.getVipLevel()!= null && d.getVipLevel() == 0).findFirst().orElse(null);
                    UserVipLevelDto user1 = list1.stream().filter(d -> d.getVipLevel()!= null && d.getVipLevel() == 1).findFirst().orElse(null);
                    UserVipLevelDto user2 = list1.stream().filter(d -> d.getVipLevel()!= null && d.getVipLevel() == 2).findFirst().orElse(null);
                    String uvip0Id="";
                    BigDecimal uvip0Money=BigDecimal.ZERO;
                    String uvip1Id="";
                    BigDecimal uvip1Money=BigDecimal.ZERO;
                    String uvip2Id="";
                    BigDecimal uvip2Money=BigDecimal.ZERO;

                    //计算第一级奖励
                    if(user0 != null){
                        uvip0Id = user0.getId();
                        uvip0Money = new BigDecimal(level1);
                    }

                    //计算第二级奖励
                    if(user1 != null && user0 != null){
                        //第一级第二级都存在用户
                        uvip1Id = user1.getId();
                        uvip1Money = new BigDecimal(level2);
                    }else if(user1 != null && user0 == null){
                        //第一级无 第二级有
                        uvip1Id = user1.getId();
                        uvip1Money = new BigDecimal(level2).add(new BigDecimal(level1));
                    }

                    //计算第三级奖励
                    if(user2 != null && user1 != null && user0 != null){
                        //一,二,三,级都有用户
                        uvip2Id = user2.getId();
                        uvip2Money = new BigDecimal(level3);
                    }else if(user2 != null && user1 == null && user0 != null){
                        //1和3级有用户,2级无用户
                        uvip2Id = user2.getId();
                        uvip2Money = new BigDecimal(level3).add(new BigDecimal(level2));
                    }else if(user2 != null && user1 != null && user0 == null){
                        //2和3级有用户,1级无用户
                        uvip2Id = user2.getId();
                        uvip2Money = new BigDecimal(level3);
                    }

                    //发送1级奖励
                    if(StringUtils.isNotBlank(uvip0Id)){
                        User byId1 = userService.getById(uvip0Id);
                        if(byId1 != null){
                            BigDecimal distributionBonus = byId1.getDistributionBonus();

                            if( distributionBonus == null){
                                distributionBonus = BigDecimal.ZERO;
                            }

                            BigDecimal add = distributionBonus.add(uvip0Money);

                            User user = new User();
                            user.setUserId(byId1.getUserId());
                            user.setDistributionBonus(add);
                            userService.updateById(user);

                            UserFundDetail detail=new UserFundDetail();
                            detail.setUserType("tz_user");
                            detail.setUid(byId1.getUserId());
                            detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                            detail.setType(UserFundDetailEnum.TYPE_0.getValue());
                            detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                            detail.setMoney(uvip0Money);
                            detail.setResidueMoney(add);
                            detail.setTitle("一级分销奖励");
                            detail.setDetails("一级分销奖励:"+uvip0Money +", 剩余:"+add);

                            detail.setOrderNumber(byId.getOrderNumber());

                            detail.setDelFlag(0);

                            //detail.setCreateBy(userId);
                            detail.setCreateTime(new Date());

                            userFundDetailService.save(detail);
                        }
                    }

                    //发送二级奖励
                    if(StringUtils.isNotBlank(uvip1Id)){
                        User byId2 = userService.getById(uvip1Id);
                        if(byId2 != null){

                            BigDecimal distributionBonus = byId2.getDistributionBonus();

                            if( distributionBonus == null){
                                distributionBonus = BigDecimal.ZERO;
                            }

                            BigDecimal add = distributionBonus.add(uvip1Money);

                            User user = new User();
                            user.setUserId(byId2.getUserId());
                            user.setDistributionBonus(add);
                            userService.updateById(user);

                            UserFundDetail detail=new UserFundDetail();
                            detail.setUserType("tz_user");
                            detail.setUid(byId2.getUserId());
                            detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                            detail.setType(UserFundDetailEnum.TYPE_1.getValue());
                            detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                            detail.setMoney(uvip1Money);
                            detail.setResidueMoney(add);
                            detail.setTitle("二级分销奖励");
                            detail.setDetails("二级分销奖励:"+uvip1Money +", 剩余:"+add);
                            detail.setOrderNumber(byId.getOrderNumber());
                            detail.setDelFlag(0);

                            //detail.setCreateBy(userId);
                            detail.setCreateTime(new Date());

                            userFundDetailService.save(detail);
                        }
                    }

                    //发送三级奖励
                    if(StringUtils.isNotBlank(uvip2Id)){
                        User byId3 = userService.getById(uvip2Id);
                        if(byId3 != null){

                            BigDecimal distributionBonus = byId3.getDistributionBonus();

                            if( distributionBonus == null){
                                distributionBonus = BigDecimal.ZERO;
                            }

                            BigDecimal add = distributionBonus.add(uvip2Money);

                            User user = new User();
                            user.setUserId(byId3.getUserId());
                            user.setDistributionBonus(add);
                            userService.updateById(user);

                            UserFundDetail detail=new UserFundDetail();
                            detail.setUserType("tz_user");
                            detail.setUid(byId3.getUserId());
                            detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                            detail.setType(UserFundDetailEnum.TYPE_2.getValue());
                            detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                            detail.setMoney(uvip2Money);
                            detail.setResidueMoney(add);
                            detail.setTitle("三级分销奖励");
                            detail.setDetails("三级分销奖励:"+uvip2Money +", 剩余:"+add);
                            detail.setOrderNumber(byId.getOrderNumber());
                            detail.setDelFlag(0);

                            //detail.setCreateBy(userId);
                            detail.setCreateTime(new Date());

                            userFundDetailService.save(detail);
                        }
                    }
                }
            }else if(byId0.getVipLevel() == 0){
                //普通会员
                for(String prodId : collect1) {
                    grantReward2Yuan(byId0.getUserId(),byId.getOrderNumber());
                }
            }else if(byId0.getVipLevel() == 1){
                //vip
                for(String prodId : collect1) {
                    grantReward2Yuan(byId0.getUserId(),byId.getOrderNumber());
                }
            }else if(byId0.getVipLevel() == 2){
                //svip
                for(String prodId : collect1) {
                    grantReward2Yuan(byId0.getUserId(),byId.getOrderNumber());
                }
            }
        }

    }

    /**
     * 升级用户下单对老上级的奖励
     * @param uid
     */
    public void grantReward2Yuan(String uid,String orderNumber) {
        User one = userService.lambdaQuery().eq(User::getReward2YuanUid, uid).one();
        if(one != null){
            String reward2YuanMoney = getValueByConfig("reward_2_yuan_money");
            if(StringUtils.isNotBlank(reward2YuanMoney) || new BigDecimal(reward2YuanMoney).compareTo(BigDecimal.ZERO) <= 0){
                return;
            }
            BigDecimal distributionBonus = one.getDistributionBonus();

            if( distributionBonus == null){
                distributionBonus = BigDecimal.ZERO;
            }

            BigDecimal add = distributionBonus.add(new BigDecimal(reward2YuanMoney));

            User user = new User();
            user.setUserId(one.getUserId());
            user.setDistributionBonus(add);
            userService.updateById(user);

            UserFundDetail detail=new UserFundDetail();
            detail.setUserType("tz_user");
            detail.setUid(one.getUserId());
            detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
            detail.setType(UserFundDetailEnum.TYPE_5.getValue());
            detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
            detail.setMoney(new BigDecimal(reward2YuanMoney));
            detail.setResidueMoney(add);
            detail.setTitle("升级用户下单对老上级的奖励");
            detail.setDetails("升级用户下单对老上级的奖励:"+reward2YuanMoney +", 剩余:"+add);
            detail.setOrderNumber(orderNumber);
            detail.setDelFlag(0);

            //detail.setCreateBy(userId);
            detail.setCreateTime(new Date());

            userFundDetailService.save(detail);
        }
    }

    /**
     * 获取配置项
     * @param key
     * @return
     */
    public String  getValueByConfig(String key) {
        List<String> param_value = jdbcTemplate.query("select param_value from tz_sys_config where param_key = ? ", new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("param_value");
            }
        }, key);

        if(param_value.isEmpty()){
            return null;
        }else{
            return param_value.get(0);
        }
    }
}
